const {unlink, copyFile} = require('fs/promises')
const pm2 = require('pm2')

const Koa = require('koa')
const serve = require('koa-static')
const app = new Koa()

const reset = () => {
  return new Promise(resolve=> {
    pm2.connect(function(err) {
      if (err) {
        console.error(err)
        process.exit(2)
      }
      pm2.stop(0, async()=>{
        await unlink('../.tmp/data.db')
        await copyFile('../.tmp/origin.db', '../.tmp/data.db')
        pm2.restart(0, ()=>{
          pm2.disconnect()
          resolve()
        })
      })
    })
  })
}

app.use(serve(__dirname))

app.use(async (ctx) => {
  if (ctx.request.path === '/reset') {
    ctx.set('Access-Control-Allow-Origin', '*');
    await reset()
    ctx.response.body = '恢复房产数据成功';
  } else {
    ctx.response.body = '404';
  }
});

app.listen(1338, ()=>{
  console.log('1338准备好了');
})
